import 'package:dio/dio.dart';
import 'package:ride_rex/net/common_net.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

class ApiOss extends CommonApi {
  ApiOss.sign() : super('user/oss/policy');
}

class OssService {
  static Future<OssResultBean?> uploadFile(String path, {CommonProgress? progress}) async {
    if (path.empty) return null;
    dynamic json = await ApiOss.sign().get();
    OssSignBean ossSignBean = OssSignBean.fromJson(json);

    DateTime dateTime = DateTime.now();
    String fileName = path.split('/').last;
    String format = fileName.split('.').last;
    int imageTimeName = dateTime.millisecondsSinceEpoch + (dateTime.microsecondsSinceEpoch ~/ 1000000);
    String imageName = '$imageTimeName.$format';
    String host = ossSignBean.host ?? '';
    String dir = ossSignBean.dir ?? '';
    var filePath = await MultipartFile.fromFile(path, filename: fileName);
    final formData = FormData.fromMap({
      'ossaccessKeyId': ossSignBean.accessKeyId,
      'policy': ossSignBean.policy,
      'signature': ossSignBean.signature,
      'callback': ossSignBean.callback,
      'key': '$dir/$imageName',
      'file': filePath,
    });
    Dio dio = Dio();
    var response = await dio.post(host, data: formData, onSendProgress: progress);
    if (response.data != null) {
      return OssResultBean.fromJson(response.data["data"]);
    }
    return null;
  }
}

class OssSignBean {
  String? accessKeyId;
  String? policy;
  String? signature;
  String? expire;
  String? dir;
  String? host;
  String? callback;

  OssSignBean({this.accessKeyId, this.policy, this.signature, this.expire, this.dir, this.host, this.callback});

  OssSignBean.fromJson(Map<String, dynamic> json) {
    if (json["accessKeyId"] is String) {
      accessKeyId = json["accessKeyId"];
    }
    if (json["policy"] is String) {
      policy = json["policy"];
    }
    if (json["signature"] is String) {
      signature = json["signature"];
    }
    if (json["expire"] is String) {
      expire = json["expire"];
    }
    if (json["dir"] is String) {
      dir = json["dir"];
    }
    if (json["host"] is String) {
      host = json["host"];
    }
    if (json["callback"] is String) {
      callback = json["callback"];
    }
  }
}

class OssResultBean {
  String? filename;
  String? size;
  String? mimeType;
  String? width;
  String? height;

  OssResultBean({this.filename, this.size, this.mimeType, this.width, this.height});

  OssResultBean.fromJson(Map<String, dynamic> json) {
    if (json["filename"] is String) {
      filename = json["filename"];
    }
    if (json["size"] is String) {
      size = json["size"];
    }
    if (json["mimeType"] is String) {
      mimeType = json["mimeType"];
    }
    if (json["width"] is String) {
      width = json["width"];
    }
    if (json["height"] is String) {
      height = json["height"];
    }
  }
}
